# -*- coding: utf-8 -*-
"""
  @Time    : 2023/3/7 17:43
  @Author  : 
  @email   : 
  @File    : system.py
"""

from flask import Blueprint, request, jsonify, current_app, render_template
from lib.docker_manage import DockerEngine
from lib.tools import (
    byte_humanized_display,
    check_endpoint_status,
    res_403,
    res_404,
    res_500)

# 定义蓝图，路由分组
system_bp = Blueprint('system_bp', __name__, url_prefix='/docker')


@system_bp.route('/system/df/<node>', methods=['GET'])
def containers_info(node):
    """
    获取指定节点的docker空间使用情况
    :param node: 节点地址IP或域名
    :return:
    """
    current_app.logger.info("base_url: %s" % request.base_url)
    current_app.logger.info("url: %s" % request.url)
    current_app.logger.info("Selected node: %s" % node)

    endpoint = "%s:2375" % node
    res_code = check_endpoint_status(endpoint=endpoint)
    if res_code != 200:
        res_403['error'] = "tcp://%s endpoint connection failure !!!" % endpoint
        return jsonify(res_403), 403

    base_url = "tcp://%s" % endpoint
    try:
        docker_client = DockerEngine(base_url=base_url)
        df_data = docker_client.df_info()
    except Exception as e:
        current_app.logger.error(e)
        res_500['error'] = str(e)
        return jsonify(res_500), 500
    if not df_data:
        return jsonify(res_404), 404
    res_data = dict()
    res_data['Images'] = list()
    res_data['Containers'] = list()
    # byte convert
    for image_item in df_data['Images']:
        image_dict = dict()
        image_dict['RepoTags'] = image_item['RepoTags']
        image_dict['Size'] = byte_humanized_display(image_item['Size'])
        image_dict['SharedSize'] = byte_humanized_display(image_item['SharedSize'])
        image_dict['UniqueSize'] = byte_humanized_display(image_item['UniqueSize'])
        res_data['Images'].append(image_dict)
    for container_item in df_data['Containers']:
        container_dict = dict()
        container_dict['Id'] = container_item['Id']
        container_dict['Names'] = container_item['Names']
        container_dict['IPAddress'] = container_item['IPAddress']
        container_dict['State'] = container_item['State']
        container_dict['SizeRw'] = byte_humanized_display(
            container_item['SizeRw'])
        res_data['Containers'].append(container_dict)

    return render_template('df_info.html', data_items=res_data)
